﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using xTeam.HengLe.Entity;
using xTeam.Hengle.DataAccess;
using System.IO;
using ShopB2C.Entity;
using System.ComponentModel;

namespace xTeam.HengLe.Controller.Manage {
    public class ProductController : BaseController {
        #region 基础

        public ActionResult Index() {
            return RedirectToAction("List");
        }
        /// <summary>
        /// 新产品
        /// </summary>
        public ActionResult New() {
            ProductViewModel viewModel = new ProductViewModel();
            viewModel.ProductView = new Entity.EProduct() { };
            viewModel.ClassifyList = _classifyDataAccess.GetClassLisytByModuleKey("Product");

            return View("BasicPost", viewModel);
        }
        /// <summary>
        /// 编辑
        /// </summary>
        public ActionResult Edit(int productId = 0) {
            if (productId < 1)
                return RedirectToAction("New");

            EProduct product = _productDataAccess.GetBaseById(productId, 0);
            if (product == null)
                return Content("产品没找到");

            ProductViewModel viewModel = new ProductViewModel();
            viewModel.ProductView = product;
            viewModel.ClassifyList = _classifyDataAccess.GetClassLisytByModuleKey("Product");
            ViewData["ProductId"] = productId;
            return View("BasicPost", viewModel);
        }
        /// <summary>
        /// 保存基础信息
        /// </summary>
        [HttpPost]
        public ActionResult Basic(EProduct prdouct) {

            int result = _productDataAccess.SaveBase(prdouct);
            return RedirectToAction("Edit", new { productId = result });
        }
        /// <summary>
        /// 列表
        /// </summary>
        public ActionResult List(int pageIndex = 0, string key = "", int classId = 0) {
            int pageCount = 0;
            ProductViewModel viewModel = new ProductViewModel();
            viewModel.ImageRoot = _imageRoot;
            viewModel.ProductList = _productDataAccess.Search(10, pageIndex, classId, key, 0, null, ref pageCount);
            ViewData["Pager"] = this.CreatePager(Url.Action("List", new { pageIndex = "{0}" }), pageCount, pageIndex);
            return View(viewModel);
        }
        /// <summary>
        /// 删除
        /// </summary>
        [HttpPost]
        public ActionResult Delete(int productId = 0) {
            _productDataAccess.Delete(productId);
            return new EmptyResult();
        }
        /// <summary>
        /// 价格
        /// </summary>
        public ActionResult Price(int productId = 0) {
            ViewData["ProductId"] = productId;

            List<UserLevelEntity> memberDiscount = _productDataAccess.MemberDiscount(productId);
            EProduct product = _productDataAccess.GetBaseById(productId, 0);
            ProductViewModel viewModel = new ProductViewModel();
            viewModel.ProductView = product;
            viewModel.MemberDiscount = memberDiscount;
            return View(viewModel);
        }
        [HttpPost]
        public ActionResult Price(int productId = 0, decimal price = 0, decimal discount = 0) {

            // 计算折扣
            if (price <= 0) {
                price = 0;
                discount = 1;
            }
            if (price > 0)
                discount = discount / price;

            _productDataAccess.BatchDiscount(productId, price, discount);


            #region 会员打折

            // 保存会员折扣
            if (Request.Form["LevelId"] != null) {
                List<UserLevelEntity> level = new List<UserLevelEntity>();

                string[] levelIds = Request.Form.GetValues("LevelId");
                string[] memberDiscounts = Request.Form.GetValues("MemberDiscount");
                string[] isDiscounts = Request.Form.GetValues("IsDiscount");

                int levleId;
                bool isDiscount;
                decimal memberDiscount;

                for (int i = 0; i < levelIds.Length; i++) {
                    int.TryParse(levelIds[i], out levleId);
                    bool.TryParse(isDiscounts[i], out isDiscount);
                    decimal.TryParse(memberDiscounts[i], out memberDiscount);

                    // 计算折扣
                    if (price <= 0) {
                        price = 0;
                        memberDiscount = 1;
                    }

                    if (price > 0)
                        memberDiscount = memberDiscount / (decimal)price;


                    _productDataAccess.SaveMemberDiscount(new UserLevelEntity() {
                        IsDiscount = isDiscount,
                        Discount = memberDiscount,
                        LevelId = levleId,
                        Sequence = productId // 没有多余的字段了，存储产品ID
                    });
                }

            }

            #endregion

            return RedirectToAction("Price", new { productId = productId });
        }



        #endregion

        #region 图片
        /// <summary>
        /// 保存图片扩展信息
        /// </summary>
        public ActionResult AlbumItemPost() {
            if (Request.Form["ImageId"] != null) {
                string[] ids = Request.Form.GetValues("ImageId");
                string[] ss = Request.Form.GetValues("Sequence");
                string[] ts = Request.Form.GetValues("tbTitle");
                string[] des = Request.Form.GetValues("Description");

                int imageId, sequence;

                for (int i = 0; i < ids.Length; i++) {
                    int.TryParse(ids[i], out imageId);
                    int.TryParse(ss[i], out sequence);

                    _productDataAccess.UpdateImageDescription(imageId, ts[i], des[i], sequence);
                }



            }

            return new EmptyResult();
        }
        /// <summary>
        /// 从图片扩展中删除图片
        /// </summary>
        [HttpPost]
        public ActionResult DeleteImageItem() {
            if (Request.Form["ImageId"] != null) {
                string[] ids = Request.Form.GetValues("ImageId");
                List<EProductImage> imageList = _productDataAccess.DeleteImage(ids);
                //删除图片
                foreach (var item in imageList) {
                    try {
                        string fileDirectory = Server.MapPath(string.Format("{0}/{1}", _imageRoot, item.ProductId));
                        System.IO.File.Delete(string.Format("{0}/{1}", fileDirectory, item.ImageName));
                        // System.IO.File.Delete(string.Format("{0}/s_{1}", fileDirectory, item.ImageName));
                    }
                    catch (Exception e) {
                    }
                }
            }
            return new EmptyResult();
        }
        /// <summary>
        /// 图片集
        /// </summary>
        public ActionResult Album(int productid = 0) {
            ViewData["ProductId"] = productid;
            ViewData["ImageRoot"] = _imageRoot;
            List<EProductImage> imageList = _productDataAccess.GetImageList(productid);
            return View(imageList);
        }
        /// <summary>
        /// 保存图片基础信息信息
        /// </summary>
        [HttpPost]
        public ActionResult Album(
            string imageName = ""
            , string filePath = ""
            , int imageId = 0
            , bool isCover = false
            , int productId = 0) {

            imageName = string.IsNullOrEmpty(imageName) ? Path.GetFileName(filePath) : imageName;
            imageName = Server.UrlDecode(imageName);
            string sourceFileName = Server.MapPath(Server.UrlDecode(filePath));
            string destDirectory = string.Format("/{0}/{1}", _imageRoot, productId);
            string destFileName = Server.MapPath(string.Format("{0}/{1}", destDirectory, imageName));

            if (System.IO.File.Exists(sourceFileName)) {
                try {
                    //检查文件夹
                    if (!System.IO.Directory.Exists(Server.MapPath(destDirectory)))
                        System.IO.Directory.CreateDirectory(Server.MapPath(destDirectory));
                    // 移动图片
                    System.IO.File.Copy(sourceFileName, destFileName, true);

                    int result = _productDataAccess.SaveImage(new EProductImage() {
                        ImageId = (int)imageId,
                        ImageName = imageName.Trim(),
                        IsCover = (bool)isCover,
                        ProductId = productId,
                    });
                }
                catch {
                }
            }

            return new EmptyResult();
        }
        /// <summary>
        /// 设置封面
        /// </summary>
        [HttpPost]
        public ActionResult SetCover(int imageId = 0) {

            int result = _productDataAccess.SetCover(imageId);
            return new EmptyResult();
        }
        #endregion

        #region 详细描述
        /// <summary>
        /// 详细特性描述
        /// </summary>
        public ActionResult Description(int productid = 0) {
            ViewData["ProductId"] = productid;
            EProductDetails details = _productDataAccess.GetDeatails(productid);
            details.Detail = details.Description;
            details.Services = RouteData.Values["Action"].ToString();
            return View("Details", details);
        }
        /// <summary>
        /// 详细信息
        /// </summary>
        public ActionResult Details(int productid = 0) {
            ViewData["ProductId"] = productid;
            EProductDetails details = _productDataAccess.GetDeatails(productid);
            details.Detail = details.Detail;
            details.Services = RouteData.Values["Action"].ToString();
            return View("Details", details);
        }
        /// <summary>
        /// 保存详细信息
        /// </summary>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Details(EProductDetails details) {
            _productDataAccess.SaveDetails(details);
            return RedirectToAction(details.Services, new { productid = details.ProductId });
        }
        /// <summary>
        /// 服务
        /// </summary>
        public ActionResult Service(int productid = 0) {
            ViewData["ProductId"] = productid;
            EProductDetails details = _productDataAccess.GetDeatails(productid);
            details.Detail = details.Services;
            details.Services = RouteData.Values["Action"].ToString();
            return View("Details", details);
        }
        /// <summary>
        /// 包装
        /// </summary>
        public ActionResult PackList(int productid = 0) {
            ViewData["ProductId"] = productid;
            EProductDetails details = _productDataAccess.GetDeatails(productid);
            details.Detail = details.PackList;
            details.Services = RouteData.Values["Action"].ToString();
            return View("Details", details);
        }
        /// <summary>
        /// 全屏查看
        /// </summary>
        public ActionResult FullSnap(int productid = 0) {
            ViewData["ProductId"] = productid;
            EProductDetails details = _productDataAccess.GetDeatails(productid);
            details.Detail = details.FullSnap;
            details.Services = RouteData.Values["Action"].ToString();
            return View("Details", details);
        }

        #endregion

        #region 扩展属性

        /// <summary>
        /// 更多高级属性
        /// </summary>
        public ActionResult Optional([DefaultValue(0)]int productId) {
            ViewData["ProductId"] = productId;
            List<ProductExtendEntity> extendList = _productDataAccess.ProductExtendList(productId);
            return View(extendList);
        }
        /// <summary>
        /// 更多高级属性
        /// </summary>
        /// <param name="productId">关联的产品ID</param>
        [HttpPost]
        public ActionResult Optional([DefaultValue(0)]int productId, bool? c) {
            bool next = Request.QueryString["next"] != null ? true : false;
            bool front = Request.QueryString["front"] != null ? true : false;

            if (Request.Form["extendKey"] != null) {

                string[] keys = Request.Form.GetValues("extendKey");
                string[] vals = Request.Form.GetValues("extendValue");
                string[] ids = Request.Form.GetValues("extendId");
                string[] sequences = Request.Form.GetValues("Sequence");

                for (int i = 0; i < keys.Length; i++) {
                    int sequence, extendId;
                    int.TryParse(ids[i], out extendId);
                    int.TryParse(sequences[i], out sequence);

                    _productDataAccess.SaveExtend(new ProductExtendEntity() {
                        ExtendId = extendId,
                        ExtendKey = keys[i],
                        ExtendValue = vals[i],
                        Sequence = sequence,
                        ProductId = productId
                    });
                }

            }
            if (!next && !front)
                return RedirectToAction("Optional", new { ProductId = productId });

            return front
                ? RedirectToAction("Property", new { ProductId = productId })
                : RedirectToAction("Album", new { ProductId = productId });
        }
        /// <summary>
        /// 删除扩展高级属性
        /// </summary>
        public ActionResult DeleteOptional([DefaultValue(0)]int extendId) {
            _productDataAccess.DeleteExtendItem(extendId);

            return new EmptyResult();
        }

        #endregion

    }
}
